package com.jeesite.modules.config;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.BucketInfo;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.jeesite.common.idgen.IdGenerate;


public class OSSUtils {
	private static  Logger logger=LoggerFactory.getLogger(OSSUtils.class);
    private static String endpoint="http://oss-cn-beijing.aliyuncs.com";
    private static String accessKeyId="LTAI4FfopRNCz7zsnSX8GeVV";
    private static String accessKeySecret ="nIAiglN19gtgmdBlsLcqUZekuJgStY";
    private static String bucketName = "bjhylfkj";
    private static String firstKey = "my-first-key";
    private static String serverUrl="http://bjhylfkj.oss-cn-beijing.aliyuncs.com";

    /**
     * 创建Bucket
     */
    public void createBucket(){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
		if(ossClient.doesBucketExist(bucketName)){
			logger.debug("您已经创建Bucket：" + bucketName + "。");
		}else{
			logger.debug("您的Bucket不存在，创建Bucket：" + bucketName + "。");
			ossClient.createBucket(bucketName);
		}
    }
    /**
     * 查看BucketInfo
     */
    public void getBucketInfo(){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	BucketInfo info=ossClient.getBucketInfo(bucketName);
		logger.debug("Bucket " + bucketName + "的信息如下：");
		logger.debug("\t数据中心：" + info.getBucket().getLocation());
		logger.debug("\t创建时间：" + info.getBucket().getCreationDate());
		logger.debug("\t用户标志：" + info.getBucket().getOwner());
    }
    /**
     * 存入字符串
     */
    public void putStr(String str){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	//存入字符串到OSS
		InputStream is = new ByteArrayInputStream(str.getBytes());
        ossClient.putObject(bucketName, firstKey, is);
        logger.debug("Object：" + firstKey + "存入OSS成功。");
    }
    /**
     * 下载
     * @throws IOException 
     */
    public void getOject() throws IOException{
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	//下载文件
        OSSObject ossObject = ossClient.getObject(bucketName, firstKey);
        InputStream inputStream = ossObject.getObjectContent();
        StringBuilder objectContent = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            objectContent.append(line);
        }
        inputStream.close();
    }
    /**
     * 上传文件
     */
    public void putObject(String filePath){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	//上传文件
        ossClient.putObject(bucketName, firstKey, new File(filePath));
        logger.debug("Object：" + filePath + "存入OSS成功。");
    }
    /**
     * 查看文件列表
     */
    public void listObjects(){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	ObjectListing objectListing = ossClient.listObjects(bucketName);
    	List<OSSObjectSummary> objectSummary = objectListing.getObjectSummaries();
    	logger.debug("您有以下Object：");
    	for(OSSObjectSummary object:objectSummary){
    		logger.debug("\t" + object.getKey());
    	}
    }
    /**
     * 删除对象
     */
    public String deleteObject(String fileKey){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	boolean exist=ossClient.doesObjectExist(bucketName, fileKey);
    	if(!exist){
    		return "文件不存在";
    	}
    	ossClient.deleteObject(bucketName,fileKey);
    	ossClient.shutdown();
    	return "操作成功";
    }
	public List<String> uploadFile(MultipartFile[] nodeFile) throws IOException, URISyntaxException {
//		firstKey
		String folder=firstKey+"/"+new SimpleDateFormat("yyyyMMdd").format(new Date());
		OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
		List<String> result=new ArrayList<String>();
		for(MultipartFile file:nodeFile){
		  InputStream is=file.getInputStream();
		  String path=file.getOriginalFilename();
		  String type=path.substring(path.lastIndexOf("."));
		  String fileNameNew=IdGenerate.randomLong()+type;
		  //文件大小
		  Long fileSize=file.getSize();
		  //创建上传ObjectMetadata
		  ObjectMetadata metadata=new ObjectMetadata();
		  metadata.setContentLength(is.available());
		  //指定该Object被下载时网页的缓存行为
		  metadata.setCacheControl("no-cache");
		  //指定该Object下设置Header
		  metadata.setHeader("Prama", "no-cache");
		  //指定该Object被下载时的内容编码格式
          metadata.setContentEncoding("utf-8");
          //文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
          //如果没有扩展名则填默认值application/octet-stream
          metadata.setContentType(getContentType(fileNameNew));
          //指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
          metadata.setContentDisposition("filename/filesize=" + fileNameNew + "/" + fileSize + "Byte.");
          //上传文件 (上传文件流的形式)
          PutObjectResult putResult = ossClient.putObject(bucketName, folder +"/"+ fileNameNew, is, metadata);
        //解析结果
          result.add(folder +"/"+ fileNameNew);
//          URL url  = getUrl(ossClient, folder +"/"+ fileNameNew);
//          if(url!=null){
//        	  
//          }
		}
		ossClient.shutdown();
		return result;
	}
	private static URL getUrl(OSS ossClient, String key) {
        // 设置URL过期时间为100年
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);        
        return url;
    }
	private String getContentType(String fileName) {
		//文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        //默认返回类型
        return "application/octet-stream";
	}
}
